<template>
  <q-tabs
    v-model="tab"
    class="text-grey bg-white cc-nav-border"
    align="left"
    inline-label
    indicator-color="primary"
    active-color="primary"
    narrow-indicator
    @click="changeTab"
  >
    <q-tab
      v-for="nav in navList"
      :key="nav.path"
      :name="nav.path"
      :label="nav.name"
      @mouseover="mover(nav)"
      @mouseleave="mout(nav)"
    >
      <slot>
        <div>
          <q-icon
            name="close"
            class="nav-close-icon"
            @click.stop="closeTab(nav)"
            v-if="nav.path!=='/home'&&nav.path===showClose"
          />
        </div>
      </slot>
    </q-tab>
  </q-tabs>
</template>

<script>
export default {
  components: {},
  props: {
    navList: Array,
  },
  data() {
    return {
      tab: '/home',
      showClose: '',
    };
  },
  watch: {
    $route(to) {
      this.tab = to.path;
      if (this.navList.filter((nav) => nav.path === to.path).length === 0) {
        this.navList.push(to);
      }
    },
  },
  computed: {},
  methods: {
    closeTab(tab) {
      let i = 0;
      let rm = null;
      for (; i < this.navList.length; i += 1) {
        if (this.navList[i].path === tab.path) {
          rm = this.navList.splice(i, 1);
          break;
        }
      }
      // 如果删除的不是当前选定的那么就啥都不做
      if (rm && rm.length === 1 && rm[0].path !== this.tab) {
        return;
      }
      if (this.navList.length > 0) {
        if (i <= this.navList.length - 1) {
          this.tab = this.navList[i].path;
        } else {
          this.tab = this.navList[i - 1].path;
        }
        this.$emit('changeTab', this.tab);
      }
    },
    mover(nav) {
      if (nav) {
        this.showClose = nav.path;
      }
    },
    mout(nav) {
      if (nav) {
        this.showClose = '';
      }
    },
    changeTab() {
      if (this.tab !== this.$route.path) { this.$emit('changeTab', this.tab); }
    },
  },
  created() { },
  mounted() {
    this.tab = this.$route.path;
  },
};
</script>
<style lang="stylus">
.nav-close-icon
  position absolute
  right 5px
  top 5px
.cc-nav-border
  border-left 1px solid rgb(204, 204, 204)
  border-bottom  1px solid rgb(204, 204, 204)
</style>
